package xyz.shuixiangyu.movie;

import java.io.File;
import java.io.FileFilter;
import java.util.LinkedList;
import java.util.List;

/**
 * find all pictures in a directory or its sub directory
 * @author ivan
 *
 */
public class MovieReader {
	private final String src;
	private final String[] pictureFormats={"jpg","png"};
	private List<File> movies;
	
	public MovieReader(String directoryPath) {
		super();
		this.src = directoryPath;
		movies=new LinkedList<>();
	}
	
	public List<Movie> getMovies(){
		List<Movie> movieList=new LinkedList<>();
		getFiles(new File(src),f->isPicture(f));
		movies.forEach(s->{
			Movie m=fileToMovie(s);
			if(m!=null)
				movieList.add(m);
		});
		return movieList;
	}
	
	private Movie fileToMovie(File file){
		Movie m=new Movie();
		try{
			String[] movieParts=file.getName().substring(0, file.getName().lastIndexOf('.')).split("_");
			if(movieParts.length!=4)
				return null;
			m.setName(movieParts[0]);
			m.setYear(Integer.parseInt(movieParts[1]));
			m.setDirector(movieParts[2]);
			m.setRatings(Double.parseDouble(movieParts[3]));
			m.setPhoto(file.getAbsolutePath());			
		}catch(NumberFormatException e){
			return null;
		}
		return m;
	}
	
	private void getFiles(File root,FileFilter filter) {
		File[] files=root.listFiles();
		for(File file:files){
			if(filter.accept(file)){
				movies.add(file);
			}
			if(file.isDirectory()){
				getFiles(file,filter);
			}
		}
	}
	
	private boolean isPicture(File f){
		for(String format:pictureFormats){
			if(f.getName().endsWith("."+format))
				return true;
		}
		return false;
	}
}
